package com.lemon.cloud.oauth.support.core;

import com.lemon.cloud.comm.constants.OAuth2Constant;
import com.lemon.cloud.security.model.SecurityUser;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

/**
 * token 输出增强
 *
 * @author huangds
 * @date 2022/6/3
 */
public class CustomeOAuth2TokenCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> {

	/**
	 * Customize the OAuth 2.0 Token attributes.
	 * @param context the context containing the OAuth 2.0 Token attributes
	 */
	@Override
	public void customize(OAuth2TokenClaimsContext context) {
		OAuth2TokenClaimsSet.Builder claims = context.getClaims();
		claims.claim(OAuth2Constant.DETAILS_LICENSE, OAuth2Constant.PROJECT_LICENSE);
		String clientId = context.getAuthorizationGrant().getName();
		claims.claim(OAuth2ParameterNames.CLIENT_ID, clientId);
		// 客户端模式不返回具体用户信息
		if (OAuth2Constant.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType().getValue())) {
			return;
		}

		SecurityUser securityUser = (SecurityUser) context.getPrincipal().getPrincipal();
		claims.claim(OAuth2Constant.DETAILS_USER, securityUser);
		claims.claim(OAuth2Constant.USERNAME, securityUser.getUsername());
	}

}
